<?php

namespace App\Trip\Geo\Amap;

use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Cache;

class POI extends Amap
{

    /**
     * 关键字搜索
     * @param string      $keywords (keywords和types两者至少必选其一)
     * @param string      $types (keywords和types两者至少必选其一)
     * @param string|null $city 可选值：城市中文、中文全拼、citycode、adcode
     * @param int|null    $offset
     * @param int|null    $page
     * @return array
     * @throws GuzzleException
     * @throws Exception
     */
    public function searchByKeywords(string $keywords, string $types, ?string $city = '', ?int $offset = 20, ?int $page = 1): array
    {
        $url = $this->buildQuery("/v3/place/text", [
            "keywords"   => $keywords,
            "city"       => $city,
            "types"      => $types,
            "offset"     => $offset,
            "page"       => $page,
            "children"   => 1,
            "extensions" => 'all',
        ]);

        $cache_key = "POI:text:".md5($url);
        if (Cache::has($cache_key)) {
            return Cache::get($cache_key);
        }
        $resp    = $this->client->get($url);
        $content = json_decode($resp->getBody()->getContents(), true);
        if (!isset($content['pois'])) {
            throw new Exception($content['msg'] ?? '查询失败');
        }

        $pois = $content['pois'];
        Cache::put($cache_key, $pois, 2 * config('trip.ttl.day'));
        return $pois;
    }


    /**
     * 周边搜索
     * @param string $location 规则： 经度和纬度用","分割，经度在前，纬度在后，经纬度小数点后不得超过6位
     * @param string $types 多个类型用“|”分割；
     * @param int    $radius 半径 最大 50000 m
     * @return array
     * @throws GuzzleException
     */
    public function around(string $location, string $types = '190000', int $radius = 50000): array
    {
        $url = $this->buildQuery("/v3/place/around", [
            "location"   => $location,
            "types"      => $types,
            "offset"     => 10,
            "radius"     => $radius,
            "page"       => 1,
            "sortrule"   => 'distance',
            "extensions" => 'all',
        ]);


        $resp    = $this->client->get($url);
        $content = json_decode($resp->getBody()->getContents(), true);
        if (!isset($content['pois'])) {
            throw new Exception($content['msg'] ?? '查询失败');
        }

        return collect($content['pois'])
            ->map(fn($v) => [
                "pcode"    => $v['pcode'],
                "citycode" => $v['citycode'],
                "adcode"   => $v['adcode'],
                "pname"    => $v['pname'],
                "cityname" => $v['cityname'],
                "adname"   => $v['adname'],
                "location" => $v['location'],
                "name"     => $v['name'],
            ])->toArray();

    }
}